package com.github.cyf.common.util;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.util.StringUtils;

/**
 * @author chenyifan
 * @create 2024-11-26 17:47
 */
public class JsonBuilder {
    private ObjectNode rootNode;

    public JsonBuilder() {
        this.rootNode = JacksonUtil.newJSONObject();
    }

    /**
     * 向根节点插入数据，其中 key 可以通过 / 为分隔符来指定嵌套路径
     * @param key 键
     * @param value 值
     */
    public void put(String key, Object value) {
        if (!StringUtils.hasText(key)) {
            return;
        }
        if (key.startsWith("/")) {
            key = key.substring(1);
        }
        String[] splits = key.split("/");
        ObjectNode currentNode = rootNode;
        ObjectNode nextNode = null;
        for (int i = 0; i < splits.length - 1; i++) {
            String property = splits[i];
            nextNode = (ObjectNode) currentNode.get(property);
            if (nextNode == null) {
                nextNode = JacksonUtil.newJSONObject();
                currentNode.set(property, nextNode);
            }
            currentNode = nextNode;
        }
        currentNode.putPOJO(splits[splits.length - 1], value);
    }

    @Override
    public String toString() {
        return JacksonUtil.toJsonString(rootNode);
    }

    public String toFormatString() {
        return JacksonUtil.toFormatJsonString(rootNode);
    }
}